<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>图书管理系统</title>

    <!-- 引入 ECharts -->
    <script src="
https://cdn.jsdelivr.net/npm/echarts@5.6.0/dist/echarts.min.js
"></script>

    <style>
        .chart-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 600px; /* 设置一个较大的高度 */
            margin-top: 20px; /* 适当间距 */
        }

        #bookTypeChart {
            width: 100%;
            height: 80%; /* 图表占父容器的 80% 高度 */
            background-color: #fff; /* 可选：背景颜色 */
        }

        .main-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-image: url('/image/1.png'); /* 替换为你的图片地址 */
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            color: #333;
        }

        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
            z-index: 1000;

            /* 宽度调整 */
            width: 500px; /* 设置默认宽度 */
            max-width: 90vw; /* 最大不超过视口的 90% */
            box-sizing: border-box; /* 防止 padding 影响宽度计算 */
        }

        .pagination-container {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
            align-items: center;
        }

        .page-size-selector {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .page-size-selector select {
            padding: 5px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }

        .pagination-info {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .pagination-buttons {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .search-box {
            margin-bottom: 15px;
            display: flex;
            gap: 10px;
        }

        .search-box input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            flex: 1;
        }

        body {
            font-family: '微软雅黑', sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 200px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
            transition: width 0.3s ease;
        }

        .sidebar.collapsed {
            width: 60px;
        }

        .sidebar.collapsed span,
        .sidebar.collapsed h2 {
            display: none;
        }

        .sidebar h2 {
            text-align: center;
            margin-bottom: 30px;
        }

        .sidebar ul {
            list-style-type: none;
            padding: 0;
        }

        .sidebar li {
            padding: 15px 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .sidebar li:hover {
            background-color: #34495e;
        }

        .sidebar li.active {
            background-color: #3498db;
        }

        /* 主内容区域样式 */
        .main-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #f5f6fa;
        }

        .dashboard-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .welcome-message {
            font-size: 24px;
            font-weight: bold;
        }

        .user-info {
            display: flex;
            align-items: center;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background-color: #3498db;
            border-radius: 50%;
            margin-right: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-weight: bold;
        }

        /* 选项卡内容样式 */
        .tab-content {
            display: none;
            animation: fadeIn 0.5s ease;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            min-height: 70vh;
        }

        .tab-content.active {
            display: block;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 数据卡片样式 */
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 20px;
        }

        .card {
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-title {
            font-size: 16px;
            color: #7f8c8d;
        }

        .card-value {
            font-size: 28px;
            font-weight: bold;
            margin-top: 10px;
        }

        /* 表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .data-table th,
        .data-table td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
        }

        .data-table th {
            background-color: #f5f5f5;
            font-weight: bold;
        }

        .data-table tr:hover {
            background-color: #f9f9f9;
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .btn {
            background-color: #3498db;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn:hover {
            background-color: #2980b9;
        }

        .btn-secondary {
            background-color: #7f8c8d;
        }

        .btn-secondary:hover {
            background-color: #6c797d;
        }

        /* 分页样式 */
        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 5px;
        }

        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
        }

        .pagination button.active {
            background-color: #3498db;
            color: white;
            border-color: #3498db;
        }

        .autocomplete-items {
            position: absolute;
            border: 1px solid #d4d4d4;
            border-bottom: none;
            border-top: none;
            z-index: 99;
            background-color: #fff;
            max-height: 200px;
            overflow-y: auto;
        }

        .autocomplete-items div {
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #d4d4d4;
        }

        .autocomplete-items div:hover {
            background-color: #e9e9e9;
        }
    </style>
</head>

<body>
<!-- 侧边栏导航 -->
<div class="sidebar">
    <h2>图书管理系统</h2>
    <ul>
        <li class="active" data-tab="dashboard"><i class="fa fa-home"></i><span>首页</span></li>
        <li data-tab="user"><i class="fa fa-user"></i><span>用户管理</span></li>
        <li data-tab="book"><i class="fa fa-book"></i><span>图书管理</span></li>
        <li data-tab="borrow"><i class="fa fa-exchange"></i><span>借阅管理</span></li>
        <li data-tab="reservation"><i class="fa fa-calendar"></i><span>预约管理</span></li>
        <li data-tab="stats"><i class="fa fa-bar-chart"></i><span>统计报表</span></li>
        <li data-tab="settings"><i class="fa fa-cog"></i><span>系统设置</span></li>
    </ul>
</div>

<!-- 主内容区域 -->
<div class="main-content">
    <div class="dashboard-header">
        <div class="welcome-message">欢迎回来，管理员</div>
        <div class="user-info">
            <div class="user-avatar">管</div>
            <div>管理员</div>
        </div>
    </div>

    <!-- 首页仪表盘 -->
    <div id="dashboard" class="tab-content active">
        <h2>系统概览</h2>

        <!-- 数据统计卡片 -->
        <div class="stats-cards">
            <div class="card">
                <div class="card-title">总借阅量</div>
                <div class="card-value" id="totalBorrowCount">0</div>
            </div>
            <div class="card">
                <div class="card-title">逾期图书</div>
                <div class="card-value" id="totalOverdueCount">0</div>
            </div>
            <div class="card">
                <div class="card-title">注册用户</div>
                <div class="card-value" id="totalUserCount">0</div>
            </div>
        </div>
    </div>


    <!-- 添加图书模态框部分内容 -->
    <div class="modal-overlay" id="addBookModal" style="display:none;">
        <div class="modal-content">
            <h3>添加图书</h3>
            <form id="addBookForm">
                <div class="form-group">
                    <label>ISBN</label>
                    <input type="text" name="isbn" required/>
                </div>
                <div class="form-group">
                    <label>书名</label>
                    <input type="text" name="title" required/>
                </div>
                <div class="form-group">
                    <label>作者</label>
                    <input type="text" name="author" required/>
                </div>
                <div class="form-group">
                    <label>出版社</label>
                    <input type="text" name="publisher" required/>
                </div>
                <div class="form-group">
                    <label>库存</label>
                    <input type="number" name="stock" required/>
                </div>
                <div class="form-group">
                    <label>图书类型</label>
                    <input type="text" name="bookClassify" id="addBookTypeInput" required/>
                </div>
                <button type="submit" class="btn">保存</button>
                <button type="button" class="btn btn-secondary" onclick="closeAddBookModal()">取消</button>
            </form>
        </div>
    </div>

    <!-- 编辑图书模态框 -->
    <div class="modal-overlay" id="editBookModal" style="display:none;">
        <div class="modal-content">
            <h3>编辑图书</h3>
            <form id="editBookForm">
                <input type="hidden" name="id">
                <div class="form-group">
                    <label>ISBN</label>
                    <input type="text" name="isbn" required/>
                </div>
                <div class="form-group">
                    <label>书名</label>
                    <input type="text" name="title" required/>
                </div>
                <div class="form-group">
                    <label>作者</label>
                    <input type="text" name="author" required/>
                </div>
                <div class="form-group">
                    <label>出版社</label>
                    <input type="text" name="publisher" required/>
                </div>
                <div class="form-group">
                    <label>库存</label>
                    <input type="number" name="stock" required/>
                </div>
                <div class="form-group">
                    <label>图书类型</label>
                    <input type="text" name="bookClassify" id="editBookTypeInput" required/>
                </div>
                <button type="submit" class="btn">保存</button>
                <button type="button" class="btn btn-secondary" onclick="closeEditBookModal()">取消</button>
            </form>
        </div>
    </div>

    <!-- 图书管理页面 -->
    <div id="book" class="tab-content">
        <h2>图书管理</h2>

        <!-- 搜索框 -->
        <div class="search-box">
            <input type="text" id="bookTitleSearch" placeholder="书名">
            <input type="text" id="bookAuthorSearch" placeholder="作者">
            <!-- 图书类型下拉框（需要保留） -->
            <select id="bookTypeSelect">
                <option value="">全部类型</option>
                <!-- 类型数据将动态插入 -->
            </select>
            <button class="btn" onclick="searchBooks()">搜索</button>
            <button class="btn" onclick="openAddBookModal()">添加图书</button>
        </div>

        <!-- 表格 -->
        <table class="data-table" id="bookTable">
            <thead>
            <tr>
                <th>ISBN</th>
                <th>书名</th>
                <th>作者</th>
                <th>出版社</th>
                <th>图书类型</th>
                <th>库存</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody></tbody>
        </table>

        <!-- 分页区域 -->
        <div class="pagination-container">
            <div class="page-size-selector">
                <span>每页展示记录数：</span>
                <select id="bookPageSizeSelect" onchange="changeBookPageSize()">
                    <option value="5">5</option>
                    <option value="10" selected>10</option>
                    <option value="20">20</option>
                </select>
            </div>
            <div class="pagination-info">
                <span id="bookTotalRecords">共0条数据</span>
                <div class="pagination-buttons">
                    <button id="bookPrevPage" class="btn btn-secondary" onclick="prevBookPage()">上一页</button>
                    <span id="bookPageInfo">第1/1页</span>
                    <button id="bookNextPage" class="btn btn-secondary" onclick="nextBookPage()">下一页</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 用户管理页面 -->
    <div id="user" class="tab-content">
        <h2>用户管理</h2>

        <div class="search-box">
            <input type="text" id="usernameSearch" placeholder="搜索用户名">
            <input type="text" id="realNameSearch" placeholder="搜索真实姓名">
            <button class="btn" onclick="searchUsers()">搜索</button>
        </div>

        <table class="data-table" id="userTable">
            <thead>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>真实姓名</th>
                <th>联系方式</th>
                <th>注册时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <!-- 用户数据将动态插入这里 -->
            </tbody>
        </table>

        <div class="pagination-container">
            <div class="page-size-selector">
                <span>每页展示记录数：</span>
                <select id="pageSizeSelect" onchange="changePageSize()">
                    <option value="5">5</option>
                    <option value="10" selected>10</option>
                    <option value="20">20</option>
                </select>
            </div>
            <div class="pagination-info">
                <span id="totalRecords">共0条数据</span>
                <div class="pagination-buttons">
                    <button id="prevPage" class="btn btn-secondary" onclick="prevPage()">上一页</button>
                    <span id="pageInfo">第1/1页</span>
                    <button id="nextPage" class="btn btn-secondary" onclick="nextPage()">下一页</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 借阅管理页面 -->
    <div id="borrow" class="tab-content">
        <h2>借阅管理</h2>

        <div class="search-box">
            <input type="text" id="borrowUsernameSearch" placeholder="用户名">
            <input type="text" id="borrowBookNameSearch" placeholder="书名">
            <select id="borrowStatusSelect">
                <option value="">全部</option>
                <option value="0">已归还</option>
                <option value="1">未归还</option>
            </select>
            <button class="btn" onclick="searchBorrows()">搜索</button>
        </div>

        <table class="data-table" id="borrowTable">
            <thead>
            <tr>
                <th>用户名</th>
                <th>书名</th>
                <th>借阅日期</th>
                <th>借阅天数</th>
                <th>归还时间</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <!-- 分页区域 -->
        <div class="pagination-container">
            <div class="page-size-selector">
                <span>每页展示记录数：</span>
                <select id="borrowPageSizeSelect" onchange="changeBorrowPageSize()">
                    <option value="5">5</option>
                    <option value="10" selected>10</option>
                    <option value="20">20</option>
                </select>
            </div>
            <div class="pagination-info">
                <span id="borrowTotalRecords">共0条数据</span>
                <div class="pagination-buttons">
                    <button id="borrowPrevPage" class="btn btn-secondary" onclick="prevBorrowPage()">上一页</button>
                    <span id="borrowPageInfo">第1/1页</span>
                    <button id="borrowNextPage" class="btn btn-secondary" onclick="nextBorrowPage()">下一页</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 预约管理页面 -->
    <div id="reservation" class="tab-content">
        <h2>预约管理</h2>

        <!-- 搜索框 -->
        <div class="search-box">
            <input type="text" id="reserveUsername" placeholder="用户名">
            <input type="text" id="reserveBookTitle" placeholder="书名">
            <button class="btn" onclick="searchReservations()">搜索</button>
        </div>

        <!-- 表格 -->
        <table class="data-table" id="reservationTable">
            <thead>
            <tr>
                <th>预约ID</th>
                <th>书籍ID</th>
                <th>用户名</th>
                <th>书名</th>
                <th>预约日期</th>
            </tr>
            </thead>
            <tbody></tbody>
        </table>

        <!-- 分页区域 -->
        <div class="pagination-container">
            <div class="page-size-selector">
                <span>每页展示记录数：</span>
                <select id="reservePageSizeSelect" onchange="changeReservePageSize()">
                    <option value="5">5</option>
                    <option value="10" selected>10</option>
                    <option value="20">20</option>
                </select>
            </div>
            <div class="pagination-info">
                <span id="reserveTotalRecords">共0条数据</span>
                <div class="pagination-buttons">
                    <button id="reservePrevPage" class="btn btn-secondary" onclick="prevReservePage()">上一页</button>
                    <span id="reservePageInfo">第1/1页</span>
                    <button id="reserveNextPage" class="btn btn-secondary" onclick="nextReservePage()">下一页</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 统计报表页面 -->
    <div id="stats" class="tab-content">
        <h2>统计报表</h2>

        <!-- 新增饼状图区域 -->
        <div class="chart-container">
            <div id="bookTypeChart" style="width: 100%; height: 100%;"></div>
        </div>

        <div class="stats-cards">
            <div class="card">
                <div class="card-title">热门分类</div>
                <div class="card-value" id="mostClassify">加载中...</div>
            </div>
            <div class="card">
                <div class="card-title">最多借阅用户</div>
                <div class="card-value" id="mostUser">加载中...</div>
            </div>
            <div class="card">
                <div class="card-title">逾期率</div>
                <div class="card-value" id="overdueRate">加载中...</div>
            </div>
        </div>
    </div>

    <!-- 系统设置页面 -->
    <div id="settings" class="tab-content">
        <h2>系统设置</h2>
        <form id="systemSettingsForm">
            <div class="form-group">
                <label>借阅期限(天)</label>
                <input type="number" id="renewalDays" name="renewalDays">
            </div>
            <div class="form-group">
                <label>每日逾期费用(元)</label>
                <input type="number" step="0.01" id="overdueFees" name="overdueFees">
            </div>
            <button type="submit" class="btn">保存设置</button>
        </form>
    </div>
</div>

<script>
    // 初始化图书类型饼状图
    let bookTypeChartInitialized = false;

    function initBookTypeChart() {
        const chartDom = document.getElementById('bookTypeChart');
        if (!chartDom) {
            console.error('#bookTypeChart 元素不存在');
            return;
        }

        const myChart = echarts.init(chartDom);

        fetch('/book/type/count')
            .then(response => response.json())
            .then(data => {
                if (data.code === 1 && Array.isArray(data.data)) {
                    const option = {
                        tooltip: {trigger: 'item'},
                        legend: {
                            orient: 'horizontal',
                            top: 'top',
                            left: 'center',
                        },
                        series: [{
                            name: '图书类型',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {show: false},
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: 40,
                                    fontWeight: 'bold'
                                }
                            },
                            labelLine: {show: false},
                            data: data.data.map(item => ({
                                value: item.count,
                                name: item.type
                            }))
                        }]
                    };
                    myChart.setOption(option);
                    myChart.resize({
                        width: 1450,
                        height: 650
                    });
                }
            })
            .catch(error => {
                console.error('获取图书类型失败:', error);
            });
    }

    // 在 stats 标签页第一次打开时初始化
    document.querySelector('[data-tab="stats"]').addEventListener('click', () => {
        if (!bookTypeChartInitialized) {
            initBookTypeChart();
            bookTypeChartInitialized = true;
        }
    });

    // 获取逾期率
    async function fetchOverdueRate() {
        try {
            const response = await fetch('/overdueRate');
            const data = await response.json();
            if (data.code === 1) {
                document.getElementById('overdueRate').textContent = data.data || '0%';
            }
        } catch (error) {
            console.error('获取逾期率失败:', error);
        }
    }

    //  获取最多借阅用户
    async function fetchMostUser() {
        try {
            const response = await fetch('/mostUser');
            const data = await response.json();
            if (data.code === 1) {
                document.getElementById('mostUser').textContent = data.data || '无数据';
            }
        } catch (error) {
            console.error('获取最多借阅用户失败:', error);
        }
    }

    // 获取热门分类
    async function fetchMostClassify() {
        try {
            const response = await fetch('/mostClassify');
            const data = await response.json();
            if (data.code === 1) {
                document.getElementById('mostClassify').textContent = data.data || '无数据';
            }
        } catch (error) {
            console.error('获取热门分类失败:', error);
        }
    }

    // 获取总借阅量
    async function fetchTotalBorrowCount() {
        try {
            const response = await fetch('/borrowCount');
            const data = await response.json();
            if (data.code === 1) {
                document.getElementById('totalBorrowCount').textContent = data.data || 0;
            }
        } catch (error) {
            console.error('获取总借阅失败:', error);
        }
    }

    // 获取逾期数量
    async function fetchTotalOverdueCount() {
        try {
            const response = await fetch('/overdueCount');
            const data = await response.json();
            if (data.code === 1) {
                document.getElementById('totalOverdueCount').textContent = data.data || 0;
            }
        } catch (error) {
            console.error('获取逾期数量失败:', error);
        }
    }

    // 获取注册用户总数
    async function fetchTotalUserCount() {
        try {
            const response = await fetch('/userCount');
            const data = await response.json();
            if (data.code === 1) {
                document.getElementById('totalUserCount').textContent = data.data || 0;
            }
        } catch (error) {
            console.error('获取用户总数失败:', error);
        }
    }

    let borrowCurrentPage = 1;
    let borrowPageSize = 10;
    let borrowTotalRecords = 0;
    let borrowTotalPages = 1;

    // 获取借阅列表
    async function getBorrows(page = 1, size = 10, status = '', username = '', bookName = '') {
        borrowCurrentPage = Number(page) || 1;
        borrowPageSize = Number(size) || 10;

        const params = new URLSearchParams();
        params.append('page', borrowCurrentPage);
        params.append('pageSize', borrowPageSize);
        if (status !== '') params.append('status', status);
        if (username) params.append('username', username);
        if (bookName) params.append('bookName', bookName);

        try {
            const response = await fetch(`/borrow?${params.toString()}`);
            const data = await response.json();

            if (data.code === 1 && data.data) {
                const table = document.getElementById('borrowTable');
                const tbody = table?.querySelector('tbody');

                if (!tbody) {
                    console.error('tbody 元素不存在，请检查 HTML 结构');
                    return;
                }

                tbody.innerHTML = '';

                borrowTotalRecords = data.data.total;
                borrowTotalPages = Math.ceil(borrowTotalRecords / borrowPageSize);
                updateBorrowPaginationInfo();

                data.data.rows.forEach((borrow) => {
                    const row = tbody.insertRow();

                    row.insertCell(0).textContent = borrow.username || '未知用户';
                    row.insertCell(1).textContent = borrow.bookName || '未知图书';
                    row.insertCell(2).textContent = borrow.borrowingTime || '-';
                    row.insertCell(3).textContent = borrow.borrowDays || '-';

                    if (borrow.returnTime) {
                        row.insertCell(4).textContent = new Date(borrow.returnTime).toLocaleDateString();
                    } else {
                        row.insertCell(4).textContent = '未归还';
                    }

                    let statusText = '未知状态';
                    if (borrow.status === 0) {
                        statusText = '已归还';
                    } else if (borrow.status === 1) {
                        statusText = '未归还';
                    }
                    row.insertCell(5).textContent = statusText;

                    const actionCell = row.insertCell(6);
                    const delBtn = document.createElement('button');
                    delBtn.className = 'btn btn-secondary';
                    delBtn.textContent = '删除';
                    delBtn.onclick = () => deleteBorrow(borrow.id);
                    actionCell.appendChild(delBtn);
                });
            }
        } catch (error) {
            console.error('获取借阅信息失败:', error);
        }
    }


    // 切换到借阅管理时刷新数据
    document.querySelector('[data-tab="borrow"]').addEventListener('click', async () => {
        await getBorrows(1, borrowPageSize);
    });


    // 更新分页信息
    function updateBorrowPaginationInfo() {
        document.getElementById('borrowTotalRecords').textContent = `共${borrowTotalRecords}条数据`;
        document.getElementById('borrowPageInfo').textContent = `第${borrowCurrentPage}/${borrowTotalPages}页`;

        document.getElementById('borrowPrevPage').disabled = borrowCurrentPage <= 1;
        document.getElementById('borrowNextPage').disabled = borrowCurrentPage >= borrowTotalPages;
    }

    // 搜索操作
    function searchBorrows() {
        const status = document.getElementById('borrowStatusSelect').value;
        const username = document.getElementById('borrowUsernameSearch').value.trim();
        const bookName = document.getElementById('borrowBookNameSearch').value.trim();

        getBorrows(1, borrowPageSize, status, username, bookName);
    }

    // 改变每页数量
    function changeBorrowPageSize() {
        borrowPageSize = parseInt(document.getElementById('borrowPageSizeSelect').value);
        getBorrows(1, borrowPageSize);
    }

    // 上一页
    function prevBorrowPage() {
        if (borrowCurrentPage > 1) {
            getBorrows(borrowCurrentPage - 1, borrowPageSize);
        }
    }

    async function deleteBorrow(id) {
        if (!confirm('确定要删除该借阅记录吗？')) return;
        try {
            const response = await fetch(`/borrow?id=${id}`, {
                method: 'DELETE'
            });
            const data = await response.json();
            if (data.code === 1) {
                alert('删除成功');
                searchBorrows(); // 刷新列表
            } else {
                alert(data.msg || '删除失败');
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    }

    // 下一页
    function nextBorrowPage() {
        if (borrowCurrentPage < borrowTotalPages) {
            getBorrows(borrowCurrentPage + 1, borrowPageSize);
        }
    }

    // 切换到图书管理时刷新数据
    document.querySelector('[data-tab="book"]').addEventListener('click', async () => {
        await getBooks(1, 10);
    });

    // 切换到用户管理时刷新数据
    document.querySelector('[data-tab="user"]').addEventListener('click', async () => {
        await getUsers(1, 10);
    });

    //图书添加
    document.getElementById('addBookForm').addEventListener('submit', async function (e) {
        e.preventDefault();
        const formData = new FormData(this);
        const body = {};
        formData.forEach((value, key) => body[key] = value);

        // 获取用户输入的图书类型名称
        const bookTitleInput = document.querySelector('#addBookTypeInput');
        const bookTitle = bookTitleInput.value.trim();

        if (!bookTitle) {
            alert('请输入图书类型');
            return;
        }

        try {
            // 查询或创建分类
            const classify = await getOrCreateClassify(bookTitle);
            body.bookClassify = classify.id; // 使用 cId 替代 bookTitle
            delete body.bookTitle; // 删除原始的 bookTitle 字段

            const response = await fetch('/book', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(body)
            });

            const data = await response.json();
            if (data.code === 1) {
                alert('图书添加成功');
                closeAddBookModal();
                searchBooks(); // 刷新列表
            } else {
                alert(data.msg || '添加失败');
            }
        } catch (error) {
            console.error('请求失败:', error);
            alert('网络错误，请稍后重试');
        }
    });

    // 侧边栏导航切换
    document.querySelectorAll('.sidebar li').forEach(item => {
        item.addEventListener('click', function () {
            // 移除其他项的选中状态
            document.querySelectorAll('.sidebar li').forEach(li => {
                li.classList.remove('active');
            });
            // 设置当前项为选中状态
            this.classList.add('active');

            // 获取对应的标签内容ID
            const tabId = this.getAttribute('data-tab');

            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });

            // 显示当前选中的标签内容
            document.getElementById(tabId).classList.add('active');
        });
    });

    // 模拟数据表格的交互
    document.querySelectorAll('.data-table').forEach(table => {
        const rows = table.querySelectorAll('tbody tr');
        rows.forEach(row => {
            row.addEventListener('mouseenter', function () {
                this.style.backgroundColor = '#f5f5f5';
            });
            row.addEventListener('mouseleave', function () {
                this.style.backgroundColor = '';
            });
        });
    });

    // 分页按钮交互
    document.querySelectorAll('.pagination button').forEach(btn => {
        btn.addEventListener('click', function () {
            // 移除其他按钮的选中状态
            this.parentElement.querySelectorAll('button').forEach(b => {
                b.classList.remove('active');
            });
            // 设置当前按钮为选中状态
            this.classList.add('active');
        });
    });

    document.getElementById('editBookForm').addEventListener('submit', async function (e) {
        e.preventDefault();
        const formData = new FormData(this);
        const body = {};
        formData.forEach((value, key) => body[key] = value);

        // 获取用户输入的图书类型名称
        const bookTitleInput = document.querySelector('#editBookTypeInput');
        const bookTitle = bookTitleInput.value.trim();

        if (!bookTitle) {
            alert('请输入图书类型');
            return;
        }

        try {
            // 查询或创建分类
            const classify = await getOrCreateClassify(bookTitle);
            body.bookClassify = classify.id; // 使用 bookClassify 替代 cId
            delete body.bookTitle;

            const response = await fetch('/book', {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(body)
            });

            const data = await response.json();
            if (data.code === 1) {
                alert('图书更新成功');
                closeEditBookModal();
                searchBooks(); // 刷新列表
            } else {
                alert(data.msg || '更新失败');
            }
        } catch (error) {
            console.error('请求失败:', error);
            alert('网络错误，请稍后重试');
        }
    });

    // 保存系统配置
    document.getElementById('systemSettingsForm').addEventListener('submit', async function (e) {
        e.preventDefault();

        const renewalDays = document.getElementById('renewalDays').value;
        const overdueFees = document.getElementById('overdueFees').value;

        try {
            const response = await fetch('/system', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    renewalDays: renewalDays,
                    overdueFees: overdueFees
                })
            });
            const data = await response.json();
            if (data.code === 1) {
                alert('系统设置保存成功');
            } else {
                alert('保存失败: ' + (data.msg || '请稍后重试'));
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    });

    // 全局分页变量
    let currentPage = 1;
    let totalPages = 1;
    let pageSize = 10;
    let totalRecords = 0;

    // 根据 bookClassify 查询或创建分类
    async function getOrCreateClassify(bookClassify) {
        try {
            const response = await fetch('/book/classify');
            const data = await response.json();

            if (data.code === 1 && Array.isArray(data.data) && data.data.includes(bookClassify)) {
                // 类型已存在，直接返回名称作为 id
                return {id: bookClassify};
            }

            // 类型不存在，也允许继续添加（当前设计下不创建新分类）
            return {id: bookClassify};

        } catch (error) {
            console.error('分类操作失败:', error);
            throw error;
        }
    }

    // 获取用户列表
    async function getUsers(page = 1, size = 10, username = '', realName = '') {
        currentPage = Number(page) || 1;
        pageSize = Number(size) || 10;

        const params = new URLSearchParams();
        params.append('page', currentPage);
        params.append('pageSize', pageSize);
        if (username) params.append('username', username);
        if (realName) params.append('realName', realName);

        try {
            const response = await fetch(`/user?${params.toString()}`);
            const data = await response.json();

            if (data.code === 1) {
                const userTable = document.getElementById('userTable');
                const tbody = userTable.getElementsByTagName('tbody')[0];
                tbody.innerHTML = '';

                totalRecords = data.data.total;
                totalPages = Math.ceil(totalRecords / pageSize);
                updatePaginationInfo();

                data.data.rows.forEach(user => {
                    const row = tbody.insertRow();

                    const idCell = row.insertCell(0);
                    const usernameCell = row.insertCell(1);
                    const realNameCell = row.insertCell(2);
                    const phoneCell = row.insertCell(3);
                    const registerTimeCell = row.insertCell(4);
                    const actionCell = row.insertCell(5);

                    idCell.textContent = user.id;
                    usernameCell.textContent = user.username;
                    realNameCell.textContent = user.realName;
                    phoneCell.textContent = user.phone;
                    registerTimeCell.textContent = user.registerTime;

                    // 创建删除按钮
                    const delBtn = document.createElement('button');
                    delBtn.className = 'btn btn-secondary';
                    delBtn.textContent = '删除';
                    delBtn.onclick = () => deleteUser(user.id);
                    actionCell.appendChild(delBtn);
                });
            }
        } catch (error) {
            console.error('获取用户列表失败:', error);
        }
    }

    // 更新分页信息
    function updatePaginationInfo() {
        document.getElementById('totalRecords').textContent = `共${totalRecords}条数据`;
        document.getElementById('pageInfo').textContent = `第${currentPage}/${totalPages}页`;

        // 禁用/启用上一页/下一页按钮
        document.getElementById('prevPage').disabled = currentPage <= 1;
        document.getElementById('nextPage').disabled = currentPage >= totalPages;
    }

    // 改变每页记录数
    function changePageSize() {
        pageSize = parseInt(document.getElementById('pageSizeSelect').value);
        currentPage = 1; // 重置到第一页
        getUsers(currentPage, pageSize);
    }

    // 上一页
    function prevPage() {
        if (currentPage > 1) {
            getUsers(currentPage - 1, pageSize);
        }
    }

    // 下一页
    function nextPage() {
        if (currentPage < totalPages) {
            getUsers(currentPage + 1, pageSize);
        }
    }

    // 搜索用户
    async function searchUsers() {
        const username = document.getElementById('usernameSearch').value.trim();
        const realName = document.getElementById('realNameSearch').value.trim();
        await getUsers(1, pageSize, username, realName); // 搜索时从第一页开始
    }

    // 删除用户
    async function deleteUser(id) {
        if (confirm('确定要删除该用户吗？')) {
            try {
                const response = await fetch(`/user?id=${id}`, {
                    method: 'DELETE'
                });

                const data = await response.json();

                if (data.code === 1) {
                    alert('用户删除成功');
                    searchUsers(currentPage); // 刷新当前页
                } else {
                    alert(data.msg || '用户删除失败');
                }
            } catch (error) {
                console.error('删除用户错误:', error);
                alert('网络错误，请稍后重试');
            }
        }
    }

    // 全局缓存图书类型数据
    let cachedBookTypes = null;

    // 获取书籍分类
    async function loadBookTypes() {
        if (cachedBookTypes) {
            updateBookTypeSelect(cachedBookTypes);
            return;
        }

        try {
            const response = await fetch('/book/classify'); // ✅ 新接口
            const data = await response.json();
            if (data.code === 1) {
                cachedBookTypes = data.data;
                updateBookTypeSelect(data.data);
            }
        } catch (error) {
            console.error('加载书籍类型失败:', error);
        }
    }

    // 更新书籍类型选择框
    function updateBookTypeSelect(types) {
        const select = document.getElementById('bookTypeSelect');
        select.innerHTML = '<option value="">全部类型</option>';
        types.forEach(bookClassify => {
            const option = document.createElement('option');
            option.value = bookClassify;
            option.textContent = bookClassify;
            select.appendChild(option);
        });
    }

    // 获取图书列表
    async function getBooks(page = 1, size = 10, title = '', author = '', bookClassify = '') {
        try {
            currentPage = Number(page) || 1;
            pageSize = Number(size) || 10;

            const params = new URLSearchParams();
            params.append('page', currentPage);
            params.append('pageSize', pageSize);
            if (title) params.append('title', title);
            if (author) params.append('author', author);
            if (bookClassify) params.append('bookClassify', bookClassify);

            const response = await fetch(`/book?${params.toString()}`);
            const data = await response.json();

            if (data.code === 1) {
                const bookTable = document.getElementById('bookTable');
                const tbody = bookTable.getElementsByTagName('tbody')[0];
                tbody.innerHTML = '';

                totalRecords = data.data.total;
                totalPages = Math.ceil(totalRecords / pageSize);
                updateBookPaginationInfo();

                data.data.rows.forEach(book => {
                    const row = tbody.insertRow();

                    const isbnCell = row.insertCell(0);
                    const titleCell = row.insertCell(1);
                    const authorCell = row.insertCell(2);
                    const publisherCell = row.insertCell(3);
                    const typeCell = row.insertCell(4) // 新增单元格
                    const stockCell = row.insertCell(5);
                    const statusCell = row.insertCell(6);
                    const actionCell = row.insertCell(7);

                    isbnCell.textContent = book.isbn;
                    titleCell.textContent = book.title;
                    authorCell.textContent = book.author;
                    publisherCell.textContent = book.publisher;
                    // 展示图书类型名称
                    typeCell.textContent = book.bookClassify || '未知类型'; // 使用后端字段名
                    stockCell.textContent = book.stock;
                    statusCell.textContent = book.status === 1 ? '有库存' : '无库存';

                    // 创建编辑/删除按钮
                    const editBtn = document.createElement('button');
                    editBtn.className = 'btn';
                    editBtn.textContent = '编辑';
                    editBtn.onclick = () => editBook(book);

                    const delBtn = document.createElement('button');
                    delBtn.className = 'btn btn-secondary';
                    delBtn.textContent = '删除';
                    delBtn.onclick = () => deleteBook(book.id);

                    actionCell.appendChild(editBtn);
                    actionCell.appendChild(delBtn);
                });
            }
        } catch (error) {
            console.error('获取图书列表错误:', error);
        }
    }

    function updateBookPaginationInfo() {
        document.getElementById('bookTotalRecords').textContent = `共${totalRecords}条数据`;
        document.getElementById('bookPageInfo').textContent = `第${currentPage}/${totalPages}页`;

        document.getElementById('bookPrevPage').disabled = currentPage <= 1;
        document.getElementById('bookNextPage').disabled = currentPage >= totalPages;
    }

    /*书籍搜索*/
    function searchBooks() {
        const title = document.getElementById('bookTitleSearch').value.trim();
        const author = document.getElementById('bookAuthorSearch').value.trim();
        const bookClassify = document.getElementById('bookTypeSelect').value.trim(); // ✅ 替换 cId 为 bookClassify

        getBooks(1, pageSize, title, author, bookClassify); // ✅ 使用新字段
    }

    /*展示页数*/
    function changeBookPageSize() {
        pageSize = parseInt(document.getElementById('bookPageSizeSelect').value);
        currentPage = 1;
        getBooks(currentPage, pageSize);
    }

    /*上一页*/
    function prevBookPage() {
        if (currentPage > 1) {
            getBooks(currentPage - 1, pageSize);
        }
    }

    /*下一页*/
    function nextBookPage() {
        if (currentPage < totalPages) {
            getBooks(currentPage + 1, pageSize);
        }
    }

    // 编辑图书
    function editBook(book) {
        document.querySelector('#editBookForm input[name="id"]').value = book.id;
        document.querySelector('#editBookForm input[name="isbn"]').value = book.isbn;
        document.querySelector('#editBookForm input[name="title"]').value = book.title;
        document.querySelector('#editBookForm input[name="author"]').value = book.author;
        document.querySelector('#editBookForm input[name="publisher"]').value = book.publisher;
        document.querySelector('#editBookForm input[name="stock"]').value = book.stock;
        document.querySelector('#editBookForm input[name="bookClassify"]').value = book.bookClassify; // ✅ 修改这里

        document.getElementById('editBookModal').style.display = 'block';
    }

    // 删除图书
    async function deleteBook(id) {
        if (!confirm('确定要删除该图书吗？')) return;
        try {
            const response = await fetch(`/book?id=${id}`, {
                method: 'DELETE'
            });
            const data = await response.json();
            if (data.code === 1) {
                alert('图书删除成功');
                searchBooks(); // 刷新列表
            } else {
                alert(data.msg || '删除失败');
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    }

    // 图书添加
    function openAddBookModal() {
        const modal = document.getElementById('addBookModal');
        modal.style.display = 'block';
    }

    //图书添加框取消键
    function closeAddBookModal() {
        const modal = document.getElementById('addBookModal');
        modal.style.display = 'none';
    }

    // 打开/关闭编辑模态框的函数
    function openEditBookModal(book) {
        // 填充表单字段
        document.querySelector('#editBookForm input[name="id"]').value = book.id;
        document.querySelector('#editBookForm input[name="isbn"]').value = book.isbn;
        document.querySelector('#editBookForm input[name="title"]').value = book.title;
        document.querySelector('#editBookForm input[name="author"]').value = book.author;
        document.querySelector('#editBookForm input[name="publisher"]').value = book.publisher;
        document.querySelector('#editBookForm input[name="stock"]').value = book.stock;
        document.querySelector('#editBookForm input[name="bookTitle"]').value = book.bookClassify;

        // 显示模态框
        document.getElementById('editBookModal').style.display = 'block';
    }

    function closeEditBookModal() {
        const modal = document.getElementById('editBookModal');
        modal.style.display = 'none';
    }

    // 预约
    let reserveCurrentPage = 1;
    let reservePageSize = 10;
    let reserveTotalRecords = 0;
    let reserveTotalPages = 1;

    // 获取预约列表
    async function getReservations(page = 1, size = 10, username = '', bookTitle = '') {
        reserveCurrentPage = parseInt(page) || 1;
        reservePageSize = parseInt(size) || 10;

        const params = new URLSearchParams();
        params.append('page', reserveCurrentPage);
        params.append('pageSize', reservePageSize);
        if (username) params.append('username', username);
        if (bookTitle) params.append('bookTitle', bookTitle);

        try {
            const response = await fetch(`/reservation?${params.toString()}`);
            const data = await response.json();

            if (data.code === 1) {
                const table = document.getElementById('reservationTable');
                const tbody = table.getElementsByTagName('tbody')[0];
                tbody.innerHTML = '';

                // 更新全局变量
                reserveTotalRecords = data.data.total;
                reserveTotalPages = Math.ceil(reserveTotalRecords / reservePageSize);
                updateReservePaginationInfo();

                // 渲染数据
                data.data.rows.forEach(res => {
                    const row = tbody.insertRow();

                    row.insertCell(0).textContent = res.id;
                    row.insertCell(1).textContent = res.bookId;
                    row.insertCell(2).textContent = res.userName;
                    row.insertCell(3).textContent = res.bookTitle;
                    row.insertCell(4).textContent = res.reserveTime; // 假设时间格式为字符串
                });
            }
        } catch (error) {
            console.error('获取预约信息失败:', error);
        }
    }

    // 更新分页信息
    function updateReservePaginationInfo() {
        document.getElementById('reserveTotalRecords').textContent = `共${reserveTotalRecords}条数据`;
        document.getElementById('reservePageInfo').textContent = `第${reserveCurrentPage}/${reserveTotalPages}页`;

        document.getElementById('reservePrevPage').disabled = reserveCurrentPage <= 1;
        document.getElementById('reserveNextPage').disabled = reserveCurrentPage >= reserveTotalPages;
    }

    // 搜索操作
    function searchReservations() {
        const username = document.getElementById('reserveUsername').value.trim();
        const bookTitle = document.getElementById('reserveBookTitle').value.trim();
        getReservations(1, reservePageSize, username, bookTitle); // 从第一页开始
    }

    // 改变每页数量
    function changeReservePageSize() {
        reservePageSize = parseInt(document.getElementById('reservePageSizeSelect').value);
        getReservations(1, reservePageSize);
    }

    // 上一页
    function prevReservePage() {
        if (reserveCurrentPage > 1) {
            getReservations(reserveCurrentPage - 1, reservePageSize);
        }
    }

    // 下一页
    function nextReservePage() {
        if (reserveCurrentPage < reserveTotalPages) {
            getReservations(reserveCurrentPage + 1, reservePageSize);
        }
    }

    // 在页面加载时初始化自动补全
    window.addEventListener("DOMContentLoaded", async () => {
        // 用于图书类型的自动补全源数据
        let bookTypes = [];
        const fetchBookTypes = async () => {
            if (bookTypes.length > 0) return bookTypes;

            try {
                const response = await fetch('/book/classify');
                const data = await response.json();
                if (data.code === 1) {
                    if (Array.isArray(data.data)) {
                        bookTypes = data.data.map(type => type?.bookClassify || '');
                    } else {
                        bookTypes = [];
                    }
                    return bookTypes;
                }
            } catch (error) {
                console.error('获取书籍类型失败:', error);
            }
            return [];
        };

        // 初始化添加和编辑窗口的自动补全
        initAutocomplete('addBookTypeInput', 'addBookTypeAutocomplete', fetchBookTypes);
        initAutocomplete('editBookTypeInput', 'editBookTypeAutocomplete', fetchBookTypes);
    });

    // 自动补全功能初始化
    function initAutocomplete(inputId, autocompleteId, fetchSuggestions) {
        const input = document.getElementById(inputId);
        const container = document.createElement('div');
        container.id = autocompleteId;
        container.className = 'autocomplete-items';
        input.parentNode.appendChild(container);

        input.addEventListener('input', async () => {
            const query = input.value.trim();
            if (query.length < 1) {
                container.innerHTML = '';
                return;
            }

            const suggestions = await fetchSuggestions();
            const filtered = suggestions.filter(s => {
                return s && typeof s === 'string' && s.toLowerCase().includes(query.toLowerCase());
            });

            container.innerHTML = '';
            filtered.forEach(suggestion => {
                const item = document.createElement('div');
                item.textContent = suggestion;
                item.addEventListener('click', () => {
                    input.value = suggestion;
                    container.innerHTML = '';
                });
                container.appendChild(item);
            });
        });

        // 点击外部关闭下拉框
        document.addEventListener('click', function (e) {
            if (!container.contains(e.target) && e.target !== input) {
                container.innerHTML = '';
            }
        });
    }

    // 获取系统配置
    async function getSystemSettings() {
        try {
            const response = await fetch('/system', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const data = await response.json();
            if (data.code === 1) {
                // 填充表单数据
                document.getElementById('renewalDays').value = data.data.renewalDays;
                document.getElementById('overdueFees').value = data.data.overdueFees;
            } else {
                alert('获取系统配置失败: ' + (data.msg || '请稍后重试'));
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    }

    function setupSidebar() {
        document.querySelectorAll('.sidebar li').forEach(item => {
            item.addEventListener('click', function () {
                // 移除 active
                document.querySelectorAll('.sidebar li').forEach(li => li.classList.remove('active'));
                this.classList.add('active');

                const tabId = this.getAttribute('data-tab');
                document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
                document.getElementById(tabId).classList.add('active');
            });
        });
    }

    function setupTabEvents() {
        document.querySelector('[data-tab="book"]').addEventListener('click', async () => {
            await getBooks(1, 10);
        });
        document.querySelector('[data-tab="user"]').addEventListener('click', async () => {
            await getUsers(1, 10);
        });
    }


    // 页面加载时获取系统配置
    window.addEventListener("DOMContentLoaded", async () => {
        // 加载首页统计数据
        await fetchTotalBorrowCount();     // 总借阅量
        await fetchTotalOverdueCount();    // 逾期数量
        await fetchTotalUserCount();       // 注册用户数
        await fetchMostClassify();         // 获取热门分类
        await fetchMostUser();             // 获取最多借阅用户
        await fetchOverdueRate();          // 获取逾期率

        await loadBookTypes();
        await getBooks(1, 10);

        setupSidebar();
        setupTabEvents();

        // 当切换到系统设置标签时加载配置
        document.querySelector('[data-tab="settings"]').addEventListener('click', getSystemSettings);

        document.querySelector('[data-tab="reservation"]').addEventListener('click', async () => {
            await getReservations(1, 10); // 加载默认页
        });

        // 初始化借阅页面数据
        document.querySelector('[data-tab="borrow"]').addEventListener('click', async () => {
            await getBorrows(1, borrowPageSize);
        });
    });
</script>
</body>
</html>